<?php

namespace app\admin\controller\live;

use app\common\controller\Backend;
use hehe\Str;
use think\facade\Db;

/**
 * 商品管理
 */
class Temp extends Backend {
    /**
     * Goods模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Goods
     */
    protected object $model;
    protected object $goodsModel;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['name', 'brand.name'];

    public function initialize(): void {
        parent::initialize();
        $this->goodsModel = new \app\admin\model\goods\Goods;
        $this->model = new \app\admin\model\live\Temp;
    }




    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $goods_ids = [];
        $param = $this->request->param();
        $result = Db::name('live_order_temp')->where(['user_id' => $param['user_id']])->whereNull('live_id')->select();
        foreach($result as $val) {
            $goods_ids[] = $val['goods_id'];
        }

        $where = [
            ['goods.id', 'in', $goods_ids]
        ];
        $user_id = $param['user_id'];
        $list = $this->goodsModel->field($this->indexField)->with(['brand', 'temp' => function($query) use ($user_id){
            $query->where(['user_id' => $user_id])->whereNull('live_id');
        }])->alias('goods')->where($where)->select();


        foreach ($list as $key => $val) {
            $list[$key]['price'] = number_format($val['price'], 0, '.', ',');
            $list[$key]['supply_price'] = number_format($val['supply_price'], 0, '.', ',');
            $size = empty($val['size']) ? [] : explode(',', $val['size']);
            $stock = empty($val['stock']) ? [] : explode(',', $val['stock']);

            $sizeWithStock = [];
            for ($i = 0; $i < 4; $i++) {
                $sizeWithStock[] = [
                    'size' => empty($size[$i]) || $size[$i] == 'TOTAL' ? '&nbsp;' : $size[$i],
                    'stock' => empty($stock[$i]) || $i + 1 == count($stock) ? '&nbsp;' : $stock[$i],
                ];
            }
            $sizeWithStock[] = [
                'size' => empty($size[count($size) - 1]) ? ' ' : $size[count($size) - 1],
                'stock' => empty($stock[count($stock) - 1]) ? ' ' : $stock[count($stock) - 1]
            ];
            $list[$key]['size_with_stock'] = $sizeWithStock;
            $list[$key]['temp_id'] = $val['temp']['id'];
        }

        $this->success('', [
            'list' => $list,
            'remark' => get_route_remark(),
        ]);
    }




}